package com.yonghui.springsecurityoauth2demo.config;

import com.yonghui.springsecurityoauth2demo.domain.OauthAuthorizationCode;
import com.yonghui.springsecurityoauth2demo.mapper.OauthAuthorizationCodeMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.common.exceptions.InvalidGrantException;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.code.AuthorizationCodeServices;
import org.springframework.util.SerializationUtils;

import java.time.Instant;
import java.util.Date;
import java.util.UUID;

/**
 * @author he_jiebing@jiuyv.com
 * @create 2024-05-14 14:30
 */
public class MyBatisAuthorizationCodeServices implements AuthorizationCodeServices{

    @Autowired
    private OauthAuthorizationCodeMapper oauthAuthorizationCodeMapper;


    @Override
    public String createAuthorizationCode(OAuth2Authentication authentication) {
        String code = UUID.randomUUID().toString().replaceAll("-","");
        System.out.println(">>>>>>>>>>>>>>>>>code:"+code);
        //authorizationCodeStore.put(code, authentication);
        OauthAuthorizationCode record = new OauthAuthorizationCode();
        record.setCode(code);
        record.setClientId(authentication.getOAuth2Request().getClientId());
        record.setUserId(authentication.getName()); // Assuming the principal's name is user ID
        record.setAuthentication(SerializationUtils.serialize(authentication));
        Instant instant = Instant.now().plusSeconds(1 * 60); // 一分钟
        // 将Instant转换为Date
        Date dateFromInstant = Date.from(instant);
        record.setExpiry(dateFromInstant); // 10 minutes expiry

        oauthAuthorizationCodeMapper.insertSelective(record);
        return code;
    }

    @Override
    public OAuth2Authentication consumeAuthorizationCode(String code) throws InvalidGrantException {
        OauthAuthorizationCode oauthAuthorizationCode = oauthAuthorizationCodeMapper.selectByPrimaryKey(code);

        if (oauthAuthorizationCode == null) {
            return null;
        }

        // Check if the code is expired
        if (oauthAuthorizationCode.getExpiry().before(Date.from(Instant.now()))) {
            // Code is expired
            //oauthAuthorizationCodeMapper.deleteByPrimaryKey(code); // Optionally delete the code
            return null; // Return null to indicate that the code is not valid anymore
        }

        OAuth2Authentication authentication = (OAuth2Authentication)SerializationUtils.deserialize(oauthAuthorizationCode.getAuthentication());
        //oauthAuthorizationCodeMapper.deleteByPrimaryKey(code);
        return authentication;
    }
}
